package com.bazaaroid.server.gae.security;

import java.io.Serializable;

import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.userdetails.UserDetails;

import com.bazaaroid.server.gae.core.persistence.model.User;
import com.bazaaroid.server.gae.security.enums.Authorities;

@SuppressWarnings("serial")
public class LoginInfo implements UserDetails, Serializable {

	private final String username;
	private final String password;
	private final String authority;
	private final boolean accountNonExpired;
	private final boolean accountNonLocked;
	private final boolean credentialsNonExpired;
	private final boolean enabled;

	public LoginInfo(User user) {
		this.username = user.getUsername();
		this.password = user.getPassword();
		this.authority = Authorities.getAuthorityFromValue(user.getType());
		this.accountNonExpired = user.isAccountNonExpired();
		this.accountNonLocked = user.isAccountNonLocked();
		this.credentialsNonExpired = user.isCredentialsNonExpired();
		this.enabled = user.isEnabled();
	}

	public GrantedAuthority[] getAuthorities() {
		return new GrantedAuthority[] { new GrantedAuthorityImpl(authority) };
	}

	public String getPassword() {
		return password;
	}

	public String getUsername() {
		return username;
	}

	public boolean isAccountNonExpired() {
		return accountNonExpired;
	}

	public boolean isAccountNonLocked() {
		return accountNonLocked;
	}

	public boolean isCredentialsNonExpired() {
		return credentialsNonExpired;
	}

	public boolean isEnabled() {
		return enabled;
	}

	@Override
	public String toString() {
		return "LoginInfo: " + username;
	}

	/**
	 * 
	 * @return Current logged in user
	 */
	public static LoginInfo getCurrentUser() {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (principal instanceof LoginInfo) {
			return (LoginInfo) principal;
		}
		return null;
	}
}
